<template>
  <!-- 产量规格管理 -->
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="45"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
        @sort-change="changeTableSort"
      >
        <el-table-column type="selection" width="55" :selectable="row => { return !row.indflag }" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="standardName" label="规格名称" />
        <el-table-column prop="plantVarietyName" label="品种名称" />
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.standardNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(45,'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(45,'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '产量规格信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
          :rules="rules"
        >
          <el-form-item label="类别选择:" prop="selectplantlist" class="w50p">
              <el-cascader
                v-model="formData.selectplantlist"
                props.checkStrictly = true
                :options="planttypeList"
                placeholder="请选择"
                :props="{ expandTrigger: 'hover',value: 'plantTypeNo',children:'children',label:'plantTypeName',checkStrictly: true}"
                @change="getpingzghong"
              />
          </el-form-item>
          <el-form-item class="w50p" label="种养品种" prop="plantVarietyNo">
              <el-select
                v-model="formData.plantVarietyNo"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item,index) in nowvarietyList"
                  :key="index"
                  :label="item.plantVarietyName"
                  :value="item.plantVarietyNo"
                />
              </el-select>
            </el-form-item>
          <el-form-item label="规格名称:" prop="standardName" class="w100p">
            <el-input v-model="formData.standardName" placeholder="请输入规格名称" clearable />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/production-statistics/production-specification-management";
// import batcjreq from "@/api/digital-production/production-batch-manage/production-batch-query"
import zhongyangleibie from "@/api/basic-info-manage/category-management/index";
import zhongyangpizhong from "@/api/basic-info-manage/breed-varieties-management/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixin";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
export default {
  name: "ProductionSpecificationManagement",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '规格名称',
          prop: 'standardName',
          type: 'input',
        }
      ],
      searchlist: {},
      // 下拉选择框相关
      formData: {
        selectplantlist: [],
        plantVarietyNo: '',
        standardName: ''
      },
      nowplantTypeName: "种养类别",
      planttypeList: [],
      nowvarietyList: [],
      // 选中的数据项数组
      nowselectedList: [],
      dialogTitle: null,
      dialogFormVisible: false,
      rules: {
        standardName: [
          { required: true, message: "规格名称不能为空", trigger: ['change','blur'] },
        ],
        plantVarietyNo: [
          { required: true, message: "品种不能为空", trigger: ['change','blur'] },
        ],
        selectplantlist: [
          { required: true, message: "类别不能为空", trigger: ['change','blur'] },
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {},
  mounted() {
    this.getTableDataList();
    this.getselectdatalist();
  },
  methods: {
    // 获取下拉框数据
    getselectdatalist() {
      // 获取种养类别列表
      // 获取种养类别树状表
      zhongyangleibie.getplantingTypeTree().then(res => {
        let list = res.data;
        this.planttypeList = list;
      })
    },
    // 通过种养类别id查品种
    getpingzghong(e) {
      let params = {
        plantTypeNo: this.formData.selectplantlist[this.formData.selectplantlist.length - 1]
      };
      zhongyangpizhong.querybycondition(params).then(res => {
        this.nowvarietyList = res.data;
      });
    },
    // 通过种养品种id查品种name
    getvarriety(id) {
      let params = {
        plantVarietyNo: id
      };
      zhongyangpizhong.querybycondition(params).then(res => {
        this.nowvarietyList = res.data;
      });
    },
    // 通过种养类别id查种养名称
    getpingzghongname(id) {
      let params = {
        plantingTypeId: id
      };
      zhongyangleibie.querybycondition(params).then(res => {
        this.nowplantTypeName = res.data[0].plantingTypeName;
      });
    },
    // 获取当前拥有类型表格
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          standardName: this.searchlist.standardName,
          farmingTypeNo: getToken("farmingTypeNo"),
          organizationNo: getToken("organizationNo")
        }
      };
      nowpagereq.getlisttwo(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("表格获取失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    add() {
      this.addActive = false;
      this.formData = {};
      this.openDialog("add");
    },
    handleEdit(row) {
      if (row.indflag) {
        this.$message.warning("请勿选择空数据");
        return;
      }
      this.getvarriety(row.plantingTypeNo);
      this.getpingzghongname(row.plantingTypeNo);
      this.formData = row;
      this.formData.selectplantlist = [row.plantTypeNo]
      this.openDialog("edit");
    },
    cancel() {
      this.addActive = true
      this.formData = {};
      this.$set(this,'nowvarietyList',[])
      this.$nextTick(()=>{
        this.$refs.formData.clearValidate()
      })
      this.closeDialog();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.standardNo;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) { this.delActive = true; } else this.delActive = false;
    },
    delmessage() {
      if (this.nowChanceStau === "del") {
        nowpagereq.dellist(this.nowselectedList).then(res => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.dellist([data.standardNo]).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs.formData.validate((valid) => { 
        if(valid) {
          this.formData.plantTypeNo = this.formData.selectplantlist[
          this.formData.selectplantlist.length - 1
          ];
          this.getvarriety(this.formData.plantVarietyNo);
          if (this.nowChanceStau === "add") {
            let addparams = JSON.parse(JSON.stringify(this.formData));
            // eslint-disable-next-line no-self-assign
            addparams.plantVarietyNo = addparams.plantVarietyNo;
            this.nowvarietyList.forEach(nowvarutem => {
              if (nowvarutem.plantVarietyNo === this.formData.plantVarietyNo) {
                addparams.plantVarietyName = nowvarutem.plantVarietyName;
              }
            });
            nowpagereq.addlist(addparams).then(res => {
              if (res.code === 1) {
                this.getTableDataList();
                this.cancel()
                this.closeDialog();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let editparams = JSON.parse(JSON.stringify(this.formData));
            this.nowvarietyList.forEach(nowvarutem => {
              if (nowvarutem.plantVarietyNo === this.formData.plantVarietyNo) {
                editparams.plantVarietyName = nowvarutem.plantVarietyName;
              }
            });
            // eslint-disable-next-line no-self-assign
            editparams.plantVarietyNo = editparams.plantVarietyNo;
            nowpagereq.editlist(editparams).then(res => {
              if (res.code === 1) {
                this.getTableDataList();
                this.cancel()
                this.closeDialog();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          return false
        }
      })
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>
<style lang="scss" scoped>
</style>
